import { useEffect, useState } from 'react'
import { Midi } from '@tonejs/midi'
import './App.css'
import { loadPianoSheet, Piano, PianoSheet } from './services/Piano';
import { GameLobby } from './pages/GameLobby/GameLobby';
import * as Tone from "tone";

function isMobileDevice(): boolean {
  return /Mobi|Android/i.test(window.navigator.userAgent);
}

async function requestFullscreen(): Promise<void> {
  const root = document.documentElement;
  if (root.requestFullscreen) {
    await root.requestFullscreen()
  } else if ((root as any).msRequestFullscreen) {
    await (root as any).msRequestFullscreen()
  } else if ((root as any).mozRequestFullScreen) {
    await (root as any).mozRequestFullScreen()
  } else if ((root as any).webkitRequestFullScreen) {
    await (root as any).webkitRequestFullScreen()
  }
  const screenOrientation: ScreenOrientation & { lock?: (orientation: string) => Promise<void> } = screen.orientation
    || (screen as any).mozOrientation
    || (screen as any).msOrientation;

  if (screenOrientation && screenOrientation.lock) {
    try {
      await screenOrientation.lock('landscape');
    } catch (e) {
      console.warn("Cannot lock screen orientation", e)
    }
  }
}


function App() {
  const [start, setStart] = useState(false)

  const startApp = async () => {
    await requestFullscreen();
    setStart(true);
    Tone.start();
    // startTest();
  }

  // TODO 修改启动页按钮和图标间距
  return (
    <div className="app">
      {
        start ? <GameLobby></GameLobby> : (
          <div>
            <div className="cover-icon"></div>
            <div className="start-button" onClick={startApp}>点击开始</div>
          </div>
        )
      }
    </div>
  )
}

export default App

const startTest = async () => {
  const piano = await Piano.create();

  const pianoSheet = await loadPianoSheet("test")

  // // load a midi file in the browser
  // const midi = await Midi.fromUrl("/public/test.mid");

  // const pianoSheet: PianoSheet = {
  //   tracks: midi.tracks.map(track => ({
  //     notes: track.notes.map(note => ({
  //       time: note.time,
  //       name: note.name,
  //       duration: note.duration,
  //       midi: note.duration
  //     })),
  //     duration: track.duration
  //   })),
  //   duration: midi.duration
  // }

  // console.log(pianoSheet);

  piano.playPianoSheet(pianoSheet);
}